import { defineStore } from 'pinia'

export const useBottleStore = defineStore('bottle', {
  state: () => ({
    // 我投递的瓶子
    sentBottles: [],
    // 我收到的瓶子
    receivedBottles: [],
    // 我的收藏
    collectedBottles: [],
    // 当前瓶子详情
    currentBottle: null,
    // 加载状态
    loading: false
  }),
  
  actions: {
    /**
     * 创建新瓶子
     */
    async createBottle(bottleData) {
      try {
        this.loading = true
        
        const newBottle = {
          id: 'bottle_' + Date.now(),
          type: bottleData.type, // 'public' | 'private'
          content: bottleData.content,
          isAnonymous: bottleData.isAnonymous || false,
          openTime: bottleData.openTime || null,
          status: bottleData.type === 'public' ? 'floating' : 'pending',
          createdAt: new Date().toISOString(),
          throwBackCount: 0,
          caughtCount: 0
        }
        
        // 添加到已投递列表
        this.sentBottles.unshift(newBottle)
        
        // 保存到本地存储
        this.saveSentBottlesToStorage()
        
        return { success: true, message: '瓶子投递成功', bottle: newBottle }
      } catch (error) {
        console.error('创建瓶子失败:', error)
        return { success: false, message: '创建瓶子失败' }
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 捞取瓶子
     */
    async catchBottle() {
      try {
        this.loading = true
        
        // 模拟从海洋中捞取瓶子
        const bottle = {
          id: 'sea_bottle_' + Date.now(),
          type: 'public',
          content: '你好，未来的过客。当你读到这封信时，我不知道自己身在何方，在做着什么。或许我正在为生活奔波，或许我已经实现了曾经的梦想。我只希望，那时的我没有忘记仰望星空的初心。这宇宙如此浩瀚，我们就像漂浮在其中的尘埃，偶然相遇，然后又各自远航。但正是这些短暂的交汇，定义了我们存在的坐标。愿你今晚也能看到美丽的星空，晚安。',
          isAnonymous: true,
          sender: {
            nickname: '一位匿名的宇航员',
            avatar: '🧑‍🚀'
          },
          createdAt: new Date().toISOString(),
          throwBackCount: 0,
          caughtCount: 0
        }
        
        this.currentBottle = bottle
        return { success: true, message: '捞到瓶子了', bottle: bottle }
      } catch (error) {
        console.error('捞取瓶子失败:', error)
        return { success: false, message: '捞取瓶子失败' }
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 收藏瓶子
     */
    async collectBottle(bottle) {
      try {
        // 检查收藏数量限制
        if (this.collectedBottles.length >= 500) {
          return { success: false, message: '收藏数量已达上限（500个）' }
        }
        
        // 添加到收藏列表
        const collectedBottle = {
          ...bottle,
          collectedAt: new Date().toISOString()
        }
        
        this.collectedBottles.unshift(collectedBottle)
        
        // 添加到收到列表
        const receivedBottle = {
          ...bottle,
          receivedAt: new Date().toISOString(),
          status: 'opened'
        }
        
        this.receivedBottles.unshift(receivedBottle)
        
        // 保存到本地存储
        this.saveCollectedBottlesToStorage()
        this.saveReceivedBottlesToStorage()
        
        return { success: true, message: '收藏成功' }
      } catch (error) {
        console.error('收藏瓶子失败:', error)
        return { success: false, message: '收藏瓶子失败' }
      }
    },
    
    /**
     * 扔回大海
     */
    async throwBackBottle(bottle) {
      try {
        // 增加扔回次数
        bottle.throwBackCount = (bottle.throwBackCount || 0) + 1
        
        // 检查是否超过扔回次数限制
        if (bottle.throwBackCount >= 5) {
          // 瓶子变为迷失状态
          bottle.status = 'lost'
        }
        
        return { success: true, message: '已扔回大海' }
      } catch (error) {
        console.error('扔回瓶子失败:', error)
        return { success: false, message: '扔回瓶子失败' }
      }
    },
    
    /**
     * 撤回瓶子
     */
    async recallBottle(bottleId) {
      try {
        const bottle = this.sentBottles.find(b => b.id === bottleId)
        if (!bottle) {
          return { success: false, message: '瓶子不存在' }
        }
        
        // 检查是否可以撤回
        if (bottle.status === 'opened') {
          return { success: false, message: '瓶子已被开启，无法撤回' }
        }
        
        // 逻辑删除
        bottle.status = 'recalled'
        bottle.updatedAt = new Date().toISOString()
        
        // 保存到本地存储
        this.saveSentBottlesToStorage()
        
        return { success: true, message: '撤回成功' }
      } catch (error) {
        console.error('撤回瓶子失败:', error)
        return { success: false, message: '撤回瓶子失败' }
      }
    },
    
    /**
     * 删除瓶子
     */
    async deleteBottle(bottleId, type = 'sent') {
      try {
        let targetArray
        
        switch (type) {
          case 'sent':
            targetArray = this.sentBottles
            break
          case 'received':
            targetArray = this.receivedBottles
            break
          case 'collected':
            targetArray = this.collectedBottles
            break
          default:
            return { success: false, message: '无效的瓶子类型' }
        }
        
        const index = targetArray.findIndex(b => b.id === bottleId)
        if (index === -1) {
          return { success: false, message: '瓶子不存在' }
        }
        
        // 删除瓶子
        targetArray.splice(index, 1)
        
        // 保存到本地存储
        if (type === 'sent') {
          this.saveSentBottlesToStorage()
        } else if (type === 'received') {
          this.saveReceivedBottlesToStorage()
        } else if (type === 'collected') {
          this.saveCollectedBottlesToStorage()
        }
        
        return { success: true, message: '删除成功' }
      } catch (error) {
        console.error('删除瓶子失败:', error)
        return { success: false, message: '删除瓶子失败' }
      }
    },
    
    /**
     * 从本地存储加载数据
     */
    loadFromStorage() {
      try {
        const sentBottles = uni.getStorageSync('sentBottles')
        const receivedBottles = uni.getStorageSync('receivedBottles')
        const collectedBottles = uni.getStorageSync('collectedBottles')
        
        if (sentBottles) {
          this.sentBottles = sentBottles
        }
        if (receivedBottles) {
          this.receivedBottles = receivedBottles
        }
        if (collectedBottles) {
          this.collectedBottles = collectedBottles
        }
      } catch (error) {
        console.error('加载瓶子数据失败:', error)
      }
    },
    
    /**
     * 保存已投递瓶子到本地存储
     */
    saveSentBottlesToStorage() {
      try {
        uni.setStorageSync('sentBottles', this.sentBottles)
      } catch (error) {
        console.error('保存已投递瓶子数据失败:', error)
      }
    },
    
    /**
     * 保存已收到瓶子到本地存储
     */
    saveReceivedBottlesToStorage() {
      try {
        uni.setStorageSync('receivedBottles', this.receivedBottles)
      } catch (error) {
        console.error('保存已收到瓶子数据失败:', error)
      }
    },
    
    /**
     * 保存收藏瓶子到本地存储
     */
    saveCollectedBottlesToStorage() {
      try {
        uni.setStorageSync('collectedBottles', this.collectedBottles)
      } catch (error) {
        console.error('保存收藏瓶子数据失败:', error)
      }
    },
    
    /**
     * 清空所有瓶子数据
     */
    clearAllBottles() {
      this.sentBottles = []
      this.receivedBottles = []
      this.collectedBottles = []
      this.currentBottle = null
      
      // 清除本地存储
      uni.removeStorageSync('sentBottles')
      uni.removeStorageSync('receivedBottles')
      uni.removeStorageSync('collectedBottles')
    }
  }
}) 